// orderpre.js
var common = require("../../common/utils.js");

var app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    businfo: false,
    contacts: '',
    contactschoose: '',
    totalmoeny: 0,
    iscontactschoose: false,
    isAgree: true,
    mainpage: true,
    insurance: false,
    contactpage: false,
    selected: false,
    appends: false,
    insureResult: false,
    isSelect: true,
    appColor: app.appColor,
    discountsData: "",
    titleList: ["添加乘车人", "选择乘意险", "使用优惠券"],
    questionList: new Array,
    discountsShow: false,
    dispriceData: app.recivePrice ? app.recivePrice : 0,
    // 提示弹出部分
    animationData: "",
    tabs: ["退票方式", "服务费", "儿童票"],
    activeIndex: 0,
    slideOffset: 0,
    tabW: 0,
    animationDetailed: "",
    detailedanimationShow: false,
    desShowBool: true,
    DesIcon: "折叠",
    workData: "",
    topHeight: app.numHeight()
  },
  
  desShow: function() {
    this.setData({
      desShowBool: !this.data.desShowBool,
      DesIcon: this.data.desShowBool ? "展开" : "折叠"
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    const that = this;
    this.setData({
      workData: app.networkData,
      questionList: app.networkData.questionList ? app.networkData.questionList : ["如何取票乘车", "退票或改签", "出票失败问题", "技术服务费"]
    })
    if (app.isRefund) {
      this.setData({
        hintData: ["支持在线退票", "服务费", "不支持儿童购票"],
        refTicket: "支持在线退票"
      })
    } else {
      this.setData({
        hintData: ["不支持在线退票", "服务费", "不支持儿童购票"],
        refTicket: "暂不支持在线退票"
      })
    }
    try {
      // 获取用户手机型号
      getModel: wx.getSystemInfo({
        success: function(res) {
          let isModel = RegExp("iPhone X").test(res.model);
          app.appmodel = isModel;
          that.setData({
            model: isModel
          })
        },
      })
      wx.getStorage({
        key: 'busLineData',
        success: function(res) {
          if (res.data) {
            wx.getStorage({
              key: 'globalcode',
              success: function(res) {
                let busData = res;
                that.discountsList(res.data, busData.NumberOfBus, busData.BusDate, busData.DestinationName)
              },
            })
            let isbao = res.data.isbao,
              cityData = res.data,
              StationList = ["郑州中心站", "郑州北站", "郑州高铁枢纽站", "焦作客运总站", "安阳中心站"];
            // 用于控制城际公交是否显示
            let prompt = false;
            for (var i = 0; i < StationList.length; i++) {
              if (StationList[i] == cityData.StationName && cityData.DestinationName == "晋城" || cityData.DestinationName == "长治") {
                prompt = true;
              }
            }
            that.getBao(isbao);
            if (res.data.des && res.data.des.length > 0) {
              var des = res.data.des.replace(/#/g, "\r\n"); //把'is'替换为空字符串
              that.setData({
                businfo: res.data,
                week: "星期" + "日一二三四五六".charAt(new Date(res.data.BusDate).getDay()),
                des: des,
                prompt: prompt
              });
            } else {
              that.setData({
                businfo: res.data,
                week: "星期" + "日一二三四五六".charAt(new Date(res.data.BusDate).getDay()),
                des: "",
                prompt: prompt
              });
            }
          }
        },
      });
      wx.getSystemInfo({
        success: function(res) {
          //设置tab的宽度
          let mtabW = res.windowWidth / 4;
          that.setData({
            tabW: mtabW
          })
        }
      });
    }
    catch (err) {
      console.log(err)
    }

  },
  // 底部提示弹出框
  tabClick: function(e) {
    var that = this;
    var idIndex = e.currentTarget.id;
    var offsetW = e.currentTarget.offsetLeft; //2种方法获取距离文档左边有多少距离
    this.setData({
      activeIndex: idIndex,
      slideOffset: offsetW
    });
  },
  bindChange: function(e) {
    var current = e.detail.current;
    var offsetW = current * this.data.tabW; //2种方法获取距离文档左边有多少距离
    this.setData({
      activeIndex: current,
      slideOffset: offsetW
    });
  },
  animationkNum: function(num) {
    //创建动画
    var animation = wx.createAnimation({
      // 动画执行时间
      duration: 250,
      timingFunction: "ease",
      // 延迟执行
      delay: 0,
    });
    animation.translate(0, num).step();
    this.setData({
      animationData: animation.export(),
    })
  },
  // 弹入
  showFun: function(e) {
    this.setData({
      animationShow: true,
      activeIndex: e.currentTarget.dataset.hintindex
    });
    this.animationkNum(-80);
  },
  // 弹出
  animtionHiden: function() {
    let that = this;
    this.animationkNum(850);
    setTimeout(function() {
      that.setData({
        animationShow: false,
      });
    }, 200);
  },
  mask: function() {
    this.animtionHiden();
  },

  detailedFun: function() {
    this.setData({
      detailedanimationShow: !this.data.detailedanimationShow
    })
  },
  detailHide: function() {
    this.setData({
      detailedanimationShow: false
    })
  },
  // =======================过渡动画弹出提示结束=======================
  Doubt: function(e) {
    let index = e.currentTarget.dataset.index;
    // let title;
    // if (index == 0) {
    //   title = "如何取票";
    // } else if (index == 1) {
    //   title = "退票或改签";
    // } else if (index == 2) {
    //   title = "支付成功，出票失败";
    // } else if (index == 3) {
    //   title = "线路相同，票价不同";
    // }
    // wx.navigateTo({
    //   url: '/pages/article/article?pages=' + title,
    // })
    wx.navigateTo({
      url: '/pages/problem/problem?index=' + index,
    })
  },
  // 获取优惠列表
  discountsList: function(globalcode, busNum, startDate, targetName) {
    app.showLoadings();
    let that = this;
    wx.request({
      url: app.serviceurl + 'Order/GetMyDiscount',
      header: {
        Authorization: "Bearer " + app.accesstoken
      },
      data: {
        globalcode: globalcode,
        busNum: busNum,
        startDate: startDate,
        targetName: targetName
      },
      dataType: 'json',
      success: function(res) {
        if (!res.data.result) {
          return
        };
        that.setData({
          discountsData: res.data.discountInfo
        });
      },
      fail: function() {
        console.log("调用失败");
      },
      complete: function() {
        app.hideLoadings();
      }
    })
  },
  // 领取优惠
  discounts: function(e) {
    console.log(e)
    app.reciveId = e.currentTarget.dataset.receiveid;
    app.recivePrice = e.currentTarget.dataset.disprice;
    this.setData({
      // 支付增加此参数
      dispriceData: e.currentTarget.dataset.disprice
    });
    this.backBtn();
  },
  more: function() {
    wx.navigateTo({
      url: '/pages/problem/problem',
    })
  },


  getBao: function(isbao) {
    var that = this;
    wx.request({
      url: app.serviceurl + 'WxMicro/QueryInsureProducts',
      header: {
        Authorization: "Bearer " + app.accesstoken
      },
      data: {
        isbao: isbao,
        TicketPrice: that.data.businfo.Price
      },
      dataType: 'json',
      success: function(res) {
        if (!res.data.Result) {
          that.setData({
            insureResult: false
          })
          return
        }
        var baoData = res.data.InsureProducts;
        var insureResult = res.data.Result;
        var trueprice = baoData.InsurePrice;
        var baoId = baoData.ProductID;
        var checked = baoData.checked;
        var isnobao = baoData.IsValid;
        var count;

        if (typeof(baoData) != 'undefined' && baoData != null) {
          baoData.forEach(function(item, i) {
            item.checked = false;
            if (baoData[i].IsSelected) {
              baoData[i].checked = true;
              count = i;
              trueprice = baoData[i].InsurePrice;
              baoId = baoData[i].ProductID;
              checked = baoData[i].checked;
              isnobao = baoData[i].IsValid;
            }
          })
        }

        that.setData({
          insureResult: true,
          baoData: baoData,
          trueprice: trueprice,
          baoId: baoId,
          checked: checked,
          isnobao: isnobao,
          // 默认数据
          baoprice: res.data.InsureProducts[count].IsFree ? 0 : res.data.InsureProducts[count].InsurePrice,
        })


      },
      fail: function() {
        console.log("调用失败");
      },
      complete: function() {
        app.hideLoadings();
      }
    })
  },

  getTakeman: function() {
    var that = this;
    wx.request({
      url: app.serviceurl + 'Member/GetTakeman',
      header: {
        Authorization: "Bearer " + app.accesstoken
      },
      data: {},
      dataType: 'json',
      success: function(res) {
        if (!res.data.Result) {
          return
        };
        if (res.data.TakeManList != null && typeof(res.data.TakeManList) != 'undefined' && res.data.TakeManList.length > 0) {
          res.data.TakeManList.forEach(function(item) {
            item.TakeManPhone = item.TakeManPhone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2');
            item.TakeManCardId = item.TakeManCardId.replace(/(\d{6})\d{4}(\d{4})/, '$1****$2');
          })
          for (var i = 0, lenI = res.data.TakeManList.length; i < lenI; ++i) {
            res.data.TakeManList[i].TakeManPhone = false;
          }
        }
        that.setData({
          contacts: res.data.TakeManList
        });
      },
      fail: function() {
        console.log("调用失败");
      },
      complete: function() {
        app.hideLoadings();
      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },


  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    this.getTakeman();
    if (app.busHint) {
      wx.showModal({
        title: "预定占座成功",
        content: "请在未完成订单中处理该订单，否则5分钟内无法重复预定！",
        showCancel: false,
        confirmText: "确定",
        success: function(res) {
          app.busHint = false;
          app.busHintRepetition = true;
          wx.navigateTo({
            url: '../personcenter/orderDetails/orderDetails',
          })
        }
      })
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function(res) {
    if (res.from === 'menu') {
      return app.OnShare();
    }
  },
  // 标题选项
  titleItem: function(e) {
    let index = e.currentTarget.dataset.index;
    if (index == 0) {
      this.choosecontact();
    }
    if (index == 1) {
      this.choosebao();
    }
    if (index == 2) {
      if (this.data.discountsData.length <= 0) {
        wx.showModal({
          title: '提示',
          content: '暂无优惠券可用',
          showCancel: false
        })
        return
      }
      this.setData({
        mainpage: false,
        discountsShow: true
      })
      // this.discountsFn();
    }
  },
  // 优惠显示
  // discountsFn: function() {
  //   console.log(this.data.discountsShow)
  // },
  choosecontact: function(e) {
    this.setData({
      mainpage: false,
      contactpage: true
    });
  },
  choosebao: function(e) {
    if (!this.data.insureResult) {
      wx.showModal({
        title: '提示',
        content: '目前没有乘意险以供购买',
        showCancel: false
      })
      return
    }
    this.setData({
      mainpage: false,
      insurance: true
    })
  },

  returns: function() {
    this.setData({
      mainpage: true,
      contactpage: false,
      appends: false,
      insurance: false
    });
  },

  checkboxChange: function(e) {
    var contacts = this.data.contacts;
    for (var i = 0, lenI = contacts.length; i < lenI; ++i) {
      if (contacts[i].TakeManId == e.currentTarget.dataset.takeman) {
        contacts[i].TakeManPhone = contacts[i].TakeManPhone == true ? false : true;
      }
      if (contacts[i].TakeManPhone == true) {
        this.setData({
          selected: true
        });
      }
    }
    this.setData({
      contacts: contacts
    });
  },
  chooseconfirm: function(e) {
    var contacts = this.data.contacts;
    var tmp = [];
    var count = 0;
    this.setData({
      iscontactschoose: false
    });
    if (contacts != null && contacts != "" && typeof(contacts) != 'undefined') {
      for (var i = 0, lenI = contacts.length; i < lenI; ++i) {
        if (contacts[i].TakeManPhone == true) {
          count++;
          tmp.push(contacts[i]);
          this.setData({
            iscontactschoose: true
          });
        }
      }
      this.setData({
        count: count
      });
    }

    app.takemaninfo = tmp;
    if (this.data.insureResult) {
      var moeny = count * this.data.businfo.Price + count * this.data.baoprice;
    } else {
      var moeny = count * this.data.businfo.Price;
    }
    this.setData({
      mainpage: true,
      contactpage: false,
      contactschoose: tmp,
      count: count,
      totalmoeny: moeny,
    });
  },

  pre: function(e) {
    wx.navigateTo({
      url: '/pages/orderconfirm/orderconfirm?formId=' + e.detail.formId + '&baoId=' + this.data.baoId + '&insure=' + this.data.isnobao,
    });
  },
  // 添加更多页面显示
  append: function() {
    // this.setData({
    //   // contactpage: false,
    //   appends: true
    // })
    wx.navigateTo({
      url: '../contact/addContact/addContact',
    })
  },
  cancel: function() {
    this.setData({
      appends: false
    })
  },
  // 添加联系人
  // 获取input值
  userName: function(e) {
    this.data.TakemanName = e.detail.value
  },
  cardId: function(e) {
    this.data.TakemanCardID = e.detail.value
  },

  backBtn: function() {
    this.setData({
      mainpage: true,
      insurance: false,
      discountsShow: false
    })
  },

  //保险  /insureResult修改
  radioChange: function(e) {
    var insurancepros = this.data.insurancepros;
    var baoxian;
    if (this.data.insureResult && typeof(this.data.count) != 'undefined') {

      baoxian = this.data.count * this.data.businfo.Price + this.data.count * this.data.baoprice;
    } else if (!this.data.insureResult && typeof(this.data.count) != 'undefined') {
      baoxian = this.data.count * this.data.businfo.Price;
    } else if (this.data.insureResult && typeof(this.data.count) == 'undefined') {
      baoxian = 0;
    }
    this.setData({
      baoId: e.detail.value,
      mainpage: true,
      insurance: false,
      totalmoeny: baoxian,
    });
  },

  prices: function(e) {
    var isfree = e.currentTarget.dataset.isfree;
    var trueprice = e.currentTarget.dataset.baoprice;
    var baoprice = e.currentTarget.dataset.baoprice,
      isnobao = e.currentTarget.dataset.isnobao,
      baoidtrue = e.currentTarget.dataset.baoidtrue,
      index = e.currentTarget.dataset.index;
    if (typeof(this.data.baoData) != 'undefined' && this.data.baoData != null) {
      this.data.baoData.forEach(function(item, i) {
        item.checked = false;
        if (isfree) {
          baoprice = 0
        }
      })
    }
    this.setData({
      baoprice: baoprice,
    })
    var insurancepros = this.data.insurancepros;
    var baoxian;
    if (this.data.insureResult && typeof(this.data.count) != 'undefined') {

      baoxian = this.data.count * this.data.businfo.Price + this.data.count * this.data.baoprice;
    } else if (!this.data.insureResult && typeof(this.data.count) != 'undefined') {
      baoxian = this.data.count * this.data.businfo.Price;
    } else if (this.data.insureResult && typeof(this.data.count) == 'undefined') {
      baoxian = 0;
    }

    this.data.baoData[index].checked = true;
    this.setData({
      baoId: baoidtrue,
      baoprice: baoprice,
      trueprice: trueprice,
      isnobao: isnobao,
      baoData: this.data.baoData,
      mainpage: true,
      insurance: false,
      totalmoeny: baoxian,
    })
  }
})